import { memo, useCallback, useContext, useRef, useState } from "react";
import { Button, Empty, Spin } from "antd";
import styles from "./index.module.scss";
import EXIF from "exif-js";
import indexContext from "../../context";
import { assemblyData } from "./tools";
import MyImage from "./MyImage";
import { downloadImg } from "../../utils/downloadImg";

function ImgList() {
  const {
    photoList,
    showPhotoIndex,
    setShowPhotoIndex,
    setPhotoList,
    globalConfig,
  } = useContext(indexContext);
  const uploadInputRef = useRef<HTMLInputElement>(null);

  const [spinning, setSpinning] = useState(false);
  const [percent, setPercent] = useState(1);

  // 上传图片
  const uploadPhoto = useCallback<React.ChangeEventHandler<HTMLInputElement>>(
    async (event) => {
      if (!event.target.files?.length) return;
      setSpinning(true);
      const files = Array.from(event.target.files);
      const newPhotoList = [...photoList];
      for (let index = 0; index < files.length; index++) {
        // 限制上传个数
        if (newPhotoList.length >= globalConfig.maxPhotos) {
          setSpinning(false);
          break;
        }
        const file = files[index];
        await new Promise((res, rej) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = function (e) {
            if (!e.target?.result) return;
            const img = new Image();
            img.src = e.target.result as string;
            img.onload = function () {
              setPercent(((index + 1) / files.length) * 100);
              // 获取图片信息
              EXIF.getData(img as any, () => {
                const photoData = assemblyData(img, file.name, globalConfig);
                newPhotoList.push(photoData);
              });
              img.remove();
              res(true);
            };
            img.onerror = rej;
          };
        });
        if (index === files.length - 1) setSpinning(false);
      }
      setPhotoList(newPhotoList);
    },
    [globalConfig, photoList, setPhotoList]
  );

  // 下载图片
  const downloadImages = useCallback(async () => {
    for (let index = 0; index < photoList.length; index++) {
      const photo = photoList[index];
      await downloadImg(photo.editPhoto!, photo.name);
    }
  }, [photoList]);

  const openUpload = useCallback(() => {
    uploadInputRef.current?.click();
  }, []);

  return (
    <div className={styles.content}>
      <Spin
        spinning={spinning}
        percent={percent}
        fullscreen
        size="large"
        tip="图片加载中"
      ></Spin>
      <div className={styles.uploadPhotoBox}>
        <Button
          type="primary"
          style={{ width: "100%" }}
          onClick={openUpload}
          disabled={photoList.length >= globalConfig.maxPhotos}
        >
          上传图片
          <input
            ref={uploadInputRef}
            hidden
            type="file"
            multiple
            onChange={uploadPhoto}
            accept="image/*"
          />
        </Button>
      </div>
      <div className={styles.imgList}>
        {photoList.length === 0 ? (
          <Empty className={styles.empty} description="请上传图片" />
        ) : (
          photoList.map((item, index) => (
            <div className={styles.imgListItem} key={item.id}>
              <MyImage
                selected={showPhotoIndex === index}
                src={item.editPhoto ?? item.originalPhoto}
                onClick={() => setShowPhotoIndex(index)}
              ></MyImage>
            </div>
          ))
        )}
      </div>
      <div className={styles.uploadPhotoBox}>
        <Button
          type="primary"
          style={{ width: "100%" }}
          onClick={downloadImages}
        >
          导出图片
        </Button>
      </div>
    </div>
  );
}

export default memo(ImgList);
